package com.group.EducationalSystem.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.group.EducationalSystem.bean.College;
import com.group.EducationalSystem.bean.Course;
import com.group.EducationalSystem.bean.ExamInformation;
import com.group.EducationalSystem.bean.Root;
import com.group.EducationalSystem.bean.Score_tab;
import com.group.EducationalSystem.bean.Student;
import com.group.EducationalSystem.bean.TeacherSelfMsg;
import com.group.EducationalSystem.bean.User;
import com.group.EducationalSystem.mapper.RootMapper;
import com.group.EducationalSystem.mapper.SchoolMapper;
import com.group.EducationalSystem.mapper.TeacherMapper;
import com.group.EducationalSystem.tools.Time;


@Controller
public class SchoolController {
	
	private Time time = new Time();
	@Resource
	private SchoolMapper schoolMapper;
	@Resource
	private TeacherMapper teacherMapper;
	@Resource
	private RootMapper rootmapper;
	
	@RequestMapping("/hello")
	public String hello() {
		return "indexmodify";
	}
	
	@RequestMapping("/login")
	public String login() {
		return "login";
	}
	
	@RequestMapping("/loginin")
	public String loginin(@RequestParam("username") String account,@RequestParam("password") String password,HttpSession session,ModelMap map){
		User user = schoolMapper.getUser(account,password);
		if(user==null){
			return "login";
		}else{
			session.setAttribute("user",user);
			if(user.getPower()==1){
				map.put("image", user.getImage());
				Student student = schoolMapper.getStudent(user.getAccount());
				if(student!=null){
					map.put("name", student.getStudent_name());
					session.setAttribute("student",student);
				}else{
					map.put("name", "新用户"+user.getAccount());
				}
				map.put("msg", time.AdmissionTime(((User)session.getAttribute("user")).getAccount()));
				map.put("msg1",time.ClosingTime(((User)session.getAttribute("user")).getAccount()));
				map.put("msg2",time.Grade(((User)session.getAttribute("user")).getAccount()));
				map.put("image1",schoolMapper.getimage(((User)session.getAttribute("user")).getUser_id()));
				map.put("grade",time.GradeStatue(((User)session.getAttribute("user")).getAccount()));
				return "TemplateStudent";
			}else if(user.getPower()==2){
//				验证信息权限为老师
//				这里处理教师登录
				/*
				 * 处理流程
				 * 1.查询教师表，将教师信息存入session
				 * 2.跳转页面至教师模块
				 * 3.
				 */
				String accountTeacher = user.getAccount();
				TeacherSelfMsg teacherInfo = new TeacherSelfMsg();
				teacherInfo.setTeacher_number(accountTeacher);
//				获取老师信息
				teacherInfo =  teacherMapper.getTeacherMsgByNumber(teacherInfo);
//				信息存入session
				session.setAttribute("teacherInfo", teacherInfo);
				System.out.println(teacherInfo.toString());
				map.put("teacherInfo", teacherInfo);
				map.put("nowPage", "teacherMsgPage");
				return "TemplateTeacher";
				
			}else if(user.getPower()==3){
				map.put("image", user.getImage());
				Root root = rootmapper.getRoot(user.getAccount());
				if(root!=null){
					map.put("name", root.getRoot_name());
					session.setAttribute("root",root);
				}else{
					map.put("name", "新用户"+user.getAccount());
				}
				session.setAttribute("power", user.getPower());
				return "TemplateRoot";
			}else {
				return "indexmodify";
			}
		}
	}
	
	@RequestMapping("/student_information")
	public String student_information(HttpSession session,ModelMap map){
				User user = (User)session.getAttribute("user");
				map.put("image", user.getImage());
				Student student = schoolMapper.getStudent(user.getAccount());
				if(student!=null){
					map.put("name", student.getStudent_name());
					session.setAttribute("student",student);
				}else{
					map.put("name", "新用户"+user.getAccount());
				}
				map.put("msg", time.AdmissionTime(((User)session.getAttribute("user")).getAccount()));
				map.put("msg1",time.ClosingTime(((User)session.getAttribute("user")).getAccount()));
				map.put("msg2",time.Grade(((User)session.getAttribute("user")).getAccount()));
				map.put("image1",schoolMapper.getimage(((User)session.getAttribute("user")).getUser_id()));
				map.put("grade",time.GradeStatue(((User)session.getAttribute("user")).getAccount()));
				return "TemplateStudent";
			}
	@RequestMapping("/showImage")
	public void showImage(HttpServletResponse response,HttpSession session){
			Student student = (Student) session.getAttribute("student");
			String image1 = schoolMapper.getimage(student.getStudent_id()).toString();
			try{
				FileInputStream fis = new FileInputStream(image1);
				int i=fis.available(); //得到文件大小   
				byte data[]=new byte[i];
				fis.read(data);
				response.setContentType("image/*"); //设置返回的文件类型   
				OutputStream toClient=response.getOutputStream(); //得到向客户端输出二进制数据的对象   
				toClient.write(data);//输出数据   
				toClient.flush();
				toClient.close();
				fis.close();
			}catch(Exception e){
				e.printStackTrace();
				System.out.println("图片不存在");
			}
	}
	
	@PostMapping("/getcollege")
	@ResponseBody
	public List<College> getcollege(HttpServletResponse resp){
		//查询数据库
		List<College> list = schoolMapper.getcollege();
		return list;
	}
	
	@PostMapping("/getstudent") @ResponseBody
	public int getstudent(HttpServletResponse resp,HttpSession session,ModelMap map) throws IOException{
		//查询数据库
		Student student = schoolMapper.getStudent(((User)session.getAttribute("user")).getAccount());
		if(student==null){
			return 1;
		}else{
			return 0;
		}
		
	}
	
	@RequestMapping("student") @ResponseBody
	public int Student(HttpSession session) {
		Student student = schoolMapper.getStudent(((User)session.getAttribute("user")).getAccount());
		if(student==null){
			return 1;
		}else{
			return 0;
		}
	}
	
	
	
	@RequestMapping("/perfectstudent")
	public String perfectStudent(@RequestParam("ID_card") String ID_card,@RequestParam("phone") String phone,@RequestParam("box") String box,@RequestParam("student_name") String student_name,@RequestParam("sex") String sex,@RequestParam("home") String home,@RequestParam("college") String college,HttpSession session,ModelMap map){
		String student_number = ((User)session.getAttribute("user")).getAccount();
		College college2 = schoolMapper.getcollegebyname(college);
		Student student = new Student(student_number,student_name,home,ID_card,sex,phone,box,college2.getCollege_id());
		schoolMapper.perfectStudent(student);
		schoolMapper.uploadimage(session.getAttribute("sqlPath").toString(),((User)session.getAttribute("user")).getAccount());
		session.setAttribute("student",student);
		map.put("image",((User)session.getAttribute("user")).getImage());
		map.put("name", student.getStudent_name());
		map.put("msg", time.AdmissionTime(((User)session.getAttribute("user")).getAccount()));
		map.put("msg1",time.ClosingTime(((User)session.getAttribute("user")).getAccount()));
		map.put("msg2",time.Grade(((User)session.getAttribute("user")).getAccount()));
		map.put("image1",schoolMapper.getimage(((User)session.getAttribute("user")).getUser_id()));
		map.put("grade",time.GradeStatue(((User)session.getAttribute("user")).getAccount()));
		return "TemplateStudent";
	}
	
	@RequestMapping("/changeinformation")
	public String changeinformation(@RequestParam("changephone") String changephone,@RequestParam("changebox") String changebox,@RequestParam("changehome") String changehome,@RequestParam("changecollege") String changecollege,HttpSession session,ModelMap map){
		College college2 = schoolMapper.getcollegebyname(changecollege);
		schoolMapper.changeStudent(changephone, changebox, changehome, college2.getCollege_id(),((User)session.getAttribute("user")).getAccount());
		map.put("image",((User)session.getAttribute("user")).getImage());
		map.put("image1",schoolMapper.getimage(((User)session.getAttribute("user")).getUser_id()));
		map.put("name", ((Student)session.getAttribute("student")).getStudent_name());
		map.put("msg", time.AdmissionTime(((User)session.getAttribute("user")).getAccount()));
		map.put("msg1",time.ClosingTime(((User)session.getAttribute("user")).getAccount()));
		map.put("msg3",time.Grade(((User)session.getAttribute("user")).getAccount()));
		map.put("grade",time.GradeStatue(((User)session.getAttribute("user")).getAccount()));
		return "TemplateStudent";
	}
	
	@ResponseBody
	@RequestMapping("/queryachievement")
	public List<Score_tab> queryachievement(HttpServletResponse resp,HttpSession session){
		List<Score_tab> list = schoolMapper.getachievement(((Student)session.getAttribute("student")).getStudent_id());
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/upload")
	public void upload(MultipartFile file,HttpSession session){
		  //定义文件保存的本地路径 
		  File f = new File(this.getClass().getResource("/").getPath());
		  String localPath=f.getPath()+"/static/img/";
		  String filename=null;  
		  // 保存数据库的路径名称，即数据库中的image列 
		  String sqlPath = null; 
		  if(file!=null){
		   //用uuid随机生成一个文件裸名
		   String uuid =UUID.randomUUID().toString().replaceAll("-","");
		   //获得文件类型（可以判断如果不是图片，禁止上传）
		   //获得文件后缀名
		   int begin = file.getOriginalFilename().indexOf(".");
           int last = file.getOriginalFilename().length();
           String contentType = file.getOriginalFilename().substring(begin, last);
		   if (!contentType.equals(".jpg")) {
			    
		   } else {
		    //得到文件名（文件名由文件裸名与后缀名组合而成）
		    filename=uuid+contentType; 
		    try {
				file.transferTo(new File(localPath+filename));
			} catch (IllegalStateException e) {
				System.out.println("错误1");
			} catch (IOException e) {
				System.out.println(e);
			} 
		   }
		  }
		  //把图片的相对路径保存至数据库
		  sqlPath = localPath+filename;
		  System.out.println(sqlPath);
	}
	
	@ResponseBody
	@RequestMapping("/getCourse")
	public List<Course> getCourses(HttpSession session){
		List<Course> list = schoolMapper.getcourse(((Student)session.getAttribute("student")).getCollege_id());
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/getCourseByName")
	public void getCoursesByName(@RequestParam("name") String name,@RequestParam("teacher") String teacher,HttpSession session,HttpServletResponse resp){
		session.setAttribute("CourseName", name);
		session.setAttribute("CourseTeacher", teacher);
	}
	
	@ResponseBody
	@RequestMapping("/getCoursebyName")
	public List<Course> getCoursebyName(HttpSession session) {
		Student student = ((Student)session.getAttribute("student"));
		String name = session.getAttribute("CourseName").toString();
		String teacher = session.getAttribute("CourseTeacher").toString();
		List<Course> list = null;
		if((name.equals("")||name==null)&&(!teacher.equals(""))) {
			list = schoolMapper.getcoursebyteacher(student.getCollege_id(), teacher);
		}else if((teacher.equals("")||teacher==null)&&(!name.equals(""))) {
			list = schoolMapper.getcoursebyname(student.getCollege_id(),name);
		}else if((!name.equals(""))&&(!teacher.equals(""))) {
			list = schoolMapper.getcoursebynameandteacher(student.getCollege_id(), name, teacher);
		}else {
			list = schoolMapper.getcourse(student.getCollege_id());
		}
		return list;
	}
	
	
	@ResponseBody
	@RequestMapping("/getTest")
	public List<Score_tab> getTest(HttpSession session){
		List<Score_tab> list = schoolMapper.getachievement(((Student)session.getAttribute("student")).getStudent_id());
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/getTestInformation")
	public List<ExamInformation> getTestInformation(HttpSession session){
		List<ExamInformation> list = schoolMapper.getExamInformation(((Student)session.getAttribute("student")).getStudent_id());
		return list;
	}
	
}
